"""Filed

 [...], [params]
"""
import re

from jinja2 import Template

from models import items, CONSTRAINTS, DEFAULTS
from templates.pg import HEAD, TEMPLATE


def TYPES(columns, idx):
    j, k = idx
    for column in columns:
        if column[j][k] == 'UUID':
            column[j][k] = '{}(as_uuid=True)'.format(column[j][k])
        if column[j][k] == 'TIMESTAMP':
            column[j][k] = '{}(timezone=True)'.format(column[j][k])
    return columns


def codegen():
    regex4docs = re.compile('(\s*\|.*)$', re.M)
    
    template = Template(TEMPLATE)
    
    codes = [HEAD]
    
    for item in items:
        title = item['title']
        classname = item['classname']
        tablename = item['tablename']
        columns = [list(map(lambda x: x.split(), row.split('|'))) \
                   for row in item['columns'].split('\n') if row]
    
        docs = regex4docs.sub('', item['columns'])
        if 'docs' in item:
            docs += item['docs']
        docs = docs.replace('\n', '\n{}'.format(' '*4))
    
        params = []
        for row in columns:  # #1,1 #1,2 #1,3
            param = []
            # Constraint
            param.extend([CONSTRAINTS[x] for x in row[1][1].split(',') \
                          if x in CONSTRAINTS])
            # nullable
            if row[1][2] == 'F':
                param.append('nullable=False')
            # default
            if row[1][3] in DEFAULTS:
                param.append(DEFAULTS[row[1][3]])
            params.append(param)
    
        # TYPES
        columns = TYPES(columns, idx=(1, 0))
    
        code = template.render(title=title,
                               docs=docs,
                               classname=classname,
                               columns=list(zip(columns, params)),
                               tablename=tablename)
        codes.append(code)
    
    with open('gen/models.py', 'w') as f:
        for s in codes:
            f.write(s)


def sqlgen():
    """INSERT INTO table_name VALUES (...)
    """
    codes = []
    for item in items:
        tablename = item['tablename']
        columns = [row.split()[0] for row in item['columns'].split('\n') if row]
        values = ", ".join(["'{}'".format(c) for c in columns])
        sql = "INSERT INTO {} VALUES ({});".format(tablename, values)
        codes.append(sql)

    with open('gen/data.sql', 'w') as f:
        s = "\n".join(codes)
        f.write(s)


if __name__ == '__main__':
    codegen()
    #sqlgen()
